package com.sls.web.manager.action.game;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.json.annotations.JSON;

import com.sls.web.manager.action.SuperAction;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.common.DataUtil;
import com.sls.web.manager.common.FilterStringSpaces;
import com.sls.web.manager.common.WebTools;
import com.sls.web.manager.execption.ManagerException;
import com.sls.web.manager.game.pojo.GamePriceTemplate;
import com.sls.web.manager.game.pojo.GameSpecialPrice;
import com.sls.web.manager.game.pojo.GoodsManageInfo;
import com.sls.web.manager.game.querybean.GameSpecialPriceQuery;
import com.sls.web.manager.game.service.GamePriceTemplateService;
import com.sls.web.manager.game.service.GameSpecialPriceService;
import com.sls.web.manager.game.service.LocalGoodsNotice;
import com.sls.web.manager.page.Pagination;

/**
 * 特殊价格:增，删，查，改
 * 
 * @author gesx
 * 
 */

@Results(value = { @Result(name = "filedownload", type = "stream", params = {
		"contentType", "application/x-download", "inputName", "istream",
		"contentDisposition", "attachment;filename=${fileName}" }) })
public class GameSpecialPriceAction extends SuperAction {
	private static final long serialVersionUID = 1L;
	@Resource(name = "gamePriceService")
	private GameSpecialPriceService gamePriceService;
	@Resource(name = "gamePriceTemplateService")
	private GamePriceTemplateService templateService;
	private GameSpecialPriceQuery gameSpecialPriceQuery;
	private Pagination<?> page;
	private GameSpecialPrice gameSpecialPrice;
	private String goodsId;
	private String templateCode;
	private List<GoodsManageInfo> goodsIdList;
	private String highPrice;
	private List<String> gamePriceTemplate;
	private GamePriceTemplate gameTemplate;
	private String Id;
	private String goodsName;
	private String tempCode;
	private String goodId;
	private String brandName;
	private String fileName;// 文件名称
	private InputStream istream; // 输入流
	private String templateName;
	private List<String> templateNameList;
	private List<GamePriceTemplate> templateList;
	private List<GameSpecialPrice> specialPriceList;
	@Resource(name="localGoodsNotice")
	private LocalGoodsNotice LocalGoodsNotice;

	// 下载使用
	// @Value("${file.create.temp.dir}")
	// private String baseDir;
	// @Value("${file.server.ip}")
	// private String fileServerIp;
	// @Value("${file.server.port}")
	// private String fileServerPort;
	// @Value("${file.client}")
	// private String fileClient;
	
	/**
	 * 商品变更，主动通知下游
	 * 
	 * @return
	 * @throws Exception
	 */
	public String noticeUser() throws Exception {
		LocalGoodsNotice.noticeGoodsModify(goodsId,templateCode,getCurrentOperator());
		try {
			if (gameSpecialPriceQuery == null) {
				gameSpecialPriceQuery = new GameSpecialPriceQuery();
				gameSpecialPriceQuery.setPageSize(Constants.INIT_PAGESIZE);
				gameSpecialPriceQuery
						.setCurrentPage(Constants.INIT_CURRENTPAGE);
			}
			String templateCode = gameSpecialPriceQuery.getTemplateCode();
			String templateName = gameSpecialPriceQuery.getTemplateName();
			String goodsId = gameSpecialPriceQuery.getGoodsId();
			String brandName = gameSpecialPriceQuery.getBrandName();
			templateCode = FilterStringSpaces.checkStringHasSpace(templateCode);
			templateName = FilterStringSpaces.checkStringHasSpace(templateName);
			goodsId = FilterStringSpaces.checkStringHasSpace(goodsId);
			brandName = FilterStringSpaces.checkStringHasSpace(brandName);
			gameSpecialPriceQuery.setTemplateCode(templateCode);
			gameSpecialPriceQuery.setTemplateName(templateName);
			gameSpecialPriceQuery.setGoodsId(goodsId);
			gameSpecialPriceQuery.setBrandName(brandName);
			page = gamePriceService.queryList(gameSpecialPriceQuery,
					getCurrentOperator());
			templateNameList = this.gamePriceService
					.queryTemplateNames(getCurrentOperator());
		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}
	

	/**
	 * 分页展示
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() throws Exception {
		try {
			if (gameSpecialPriceQuery == null) {
				gameSpecialPriceQuery = new GameSpecialPriceQuery();
				gameSpecialPriceQuery.setPageSize(Constants.INIT_PAGESIZE);
				gameSpecialPriceQuery
						.setCurrentPage(Constants.INIT_CURRENTPAGE);
			}
			String templateCode = gameSpecialPriceQuery.getTemplateCode();
			String templateName = gameSpecialPriceQuery.getTemplateName();
			String goodsId = gameSpecialPriceQuery.getGoodsId();
			String brandName = gameSpecialPriceQuery.getBrandName();
			templateCode = FilterStringSpaces.checkStringHasSpace(templateCode);
			templateName = FilterStringSpaces.checkStringHasSpace(templateName);
			goodsId = FilterStringSpaces.checkStringHasSpace(goodsId);
			brandName = FilterStringSpaces.checkStringHasSpace(brandName);
			gameSpecialPriceQuery.setTemplateCode(templateCode);
			gameSpecialPriceQuery.setTemplateName(templateName);
			gameSpecialPriceQuery.setGoodsId(goodsId);
			gameSpecialPriceQuery.setBrandName(brandName);
			page = gamePriceService.queryList(gameSpecialPriceQuery,
					getCurrentOperator());
			templateNameList = this.gamePriceService
					.queryTemplateNames(getCurrentOperator());
		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}

		return LIST;

	}

	/**
	 * 跳转添加页面，同时查询所有模板名称
	 * 
	 * @return
	 * @throws Exception
	 */
	public String add() throws Exception {
		try {

			gamePriceTemplate = gamePriceService.queryTemplateNameList(
					gameTemplate, getCurrentOperator());

		} catch (ManagerException e) {
			addActionError(e.getMessage());
			return ERROR;
		}
		return INPUT;
	}

	/**
	 * 根据模板名称查询商品
	 * 
	 * @return
	 * @throws Exception
	 */
	public String query() throws Exception {
		String templateName = WebTools.getParameter("templateName");
		if (StringUtils.isNotEmpty(templateName)) {
			goodsIdList = gamePriceService.queryNotInSpecialPrice(templateName,
					getCurrentOperator());

		}
		message = WebTools.writeAjax(goodsIdList);

		return "ajax";
	}

	/**
	 * 根据商品查询商品最高价格
	 * 
	 * @return
	 * @throws Exception
	 */
	public String queryHighPrice() throws Exception {

		if (StringUtils.isNotEmpty(goodsId)) {
			highPrice = gamePriceService.queryHighInPrice(goodsId,
					getCurrentOperator());
		}
		message = WebTools.writeAjax(highPrice);
		return "ajax";
	}

	/**
	 * 校验商品是否存在对应的模板
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkGoodsName() throws Exception {
		String goodsId = gameSpecialPrice.getGoodsId();
		message = String.valueOf(gamePriceService.checkGoodsName(goodsId,
				getCurrentOperator()));
		return "ajax";
	}

	/**
	 * 保存
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception {
		try {
			gamePriceService.saveGameSpecialPrice(gameSpecialPrice,
					getCurrentOperator());
			redirectionUrl = "game_special_price!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
			query();
		}

		return "audit_success";

	}

	/**
	 * 修改跳转页面
	 * 
	 * @return
	 * @throws Exception
	 */
	public String toEdit() throws Exception {
		if (StringUtils.isNotEmpty(goodsId)
				&& StringUtils.isNotEmpty(templateCode)) {
			gameSpecialPrice = gamePriceService.queryById(goodsId,
					templateCode, getCurrentOperator());
			if (gameSpecialPrice == null) {
				return ERROR;
			}
		}
		if (StringUtils.isNotEmpty(goodsId)
				&& StringUtils.isNotEmpty(templateCode)) {
			return INPUT;
		}
		return SUCCESS;
	}

	/**
	 * 修改
	 * 
	 * @return
	 * @throws Exception
	 */
	public String edit() throws Exception {
		String inPrice = WebTools.getParameter("inPrice");
		try {
			int price = DataUtil.toInt(inPrice);
			gameSpecialPrice.setInPrice(price);
			gamePriceService.updateGameSpecialPrice(gameSpecialPrice,
					getCurrentOperator());

			if (gameSpecialPriceQuery == null) {
				gameSpecialPriceQuery = new GameSpecialPriceQuery();
				gameSpecialPriceQuery.setPageSize(Constants.INIT_PAGESIZE);
				gameSpecialPriceQuery
						.setCurrentPage(Constants.INIT_CURRENTPAGE);
			}
			if (StringUtils.isNotEmpty(goodId)) {
				gameSpecialPriceQuery.setGoodsId(goodId);
			}
			if (StringUtils.isNotEmpty(tempCode)) {
				gameSpecialPriceQuery.setTemplateCode(tempCode);
			}
			if (StringUtils.isNotEmpty(templateName)) {
				gameSpecialPriceQuery.setTemplateName(templateName);
			}
			if (StringUtils.isNotEmpty(brandName)) {
				gameSpecialPriceQuery.setBrandName(brandName);
			}
			return list();
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
			redirectionUrl = "game_special_price!list.htm";
			return SUCCESS;
		}
	}

	/**
	 * 删除
	 * 
	 * @return
	 * @throws Exception
	 */
	public String delete() throws Exception {

		try {
			gamePriceService.deleteGameSpecialPrice(Id, getCurrentOperator());
		} catch (ManagerException e) {
			addActionError(e.getMessage());
			return ERROR;
		}
		return list();

	}

	/**
	 * 根据goodsId,templateCode查询单条记录
	 * 
	 * @return
	 * @throws Exception
	 */
	public String queryById() throws Exception {
		try {
			gameSpecialPrice = gamePriceService.queryById(goodsId,
					templateCode, getCurrentOperator());
			if (gameSpecialPrice == null) {
				return ERROR;
			}
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return "detail";
	}

	public String toCopy() throws Exception {
		try {
			this.templateList = this.templateService
					.queryTemplateList(getCurrentOperator());
			this.specialPriceList = this.gamePriceService
					.queryPriceTemplateInfoList(getCurrentOperator());
		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}
		return "copy";
	}

	public String copy() throws Exception {
		try {
			this.gamePriceService.copy(gameSpecialPrice, getCurrentOperator());
			redirectionUrl = "game_special_price!list.htm";
		} catch (Exception e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 导出excel文件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String export() throws Exception {
		List<GameSpecialPrice> list = null;
		try {
			list = this.gamePriceService.querySpecialPriceInfo(templateName,
					brandName, getCurrentOperator());
		} catch (ManagerException e1) {
			addActionError(e1.getMessage());
			flag = false;
			return SUCCESS;
		}
		String filename = templateName + ".xls";
		try {
			this.createExcel(filename, list);
		} catch (IOException e) {
			addActionError("导出文件异常!");
			flag = false;
			return SUCCESS;
		}
		return "filedownload";
	}

	/**
	 * 创建excel表格
	 * 
	 * @param path
	 * @param list
	 * @throws IOException
	 */
	private void createExcel(String filenameWeb, List<GameSpecialPrice> list)
			throws IOException {
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet("模板价格信息");
		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow(0);
		// 第四步，创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("模板编号");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("模板名称");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("品牌编号");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("品牌名称");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("商品编号");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("商品名称");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("售价(元)");
		cell.setCellStyle(style);

		// 第五步，写入实体数据 实际应用中这些数据从数据库得到，
		if (list != null && !list.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {
				row = sheet.createRow((int) i + 1);
				GameSpecialPrice special = (GameSpecialPrice) list.get(i);
				// 第四步，创建单元格，并设置值
				cell = row.createCell(0);
				cell.setCellStyle(style);
				cell.setCellValue(special.getTemplateCode());
				cell = row.createCell(1);
				cell.setCellStyle(style);
				cell.setCellValue(special.getTemplateName());
				cell = row.createCell(2);
				cell.setCellStyle(style);
				cell.setCellValue(special.getBrandId());
				cell = row.createCell(3);
				cell.setCellStyle(style);
				cell.setCellValue(special.getBrandName());
				cell = row.createCell(4);
				cell.setCellStyle(style);
				cell.setCellValue(special.getGoodsId());
				cell = row.createCell(5);
				cell.setCellStyle(style);
				cell.setCellValue(special.getGoodsName());
				cell = row.createCell(6);
				cell.setCellStyle(style);
				double inPrice = special.getInPrice() * 1.0 / 1000;
				cell.setCellValue(inPrice);

			}
		}

		// 第六步，将文件存到指定位置
		// FileOutputStream fout = new FileOutputStream(path);
		// wb.write(fout);
		// fout.flush();
		// fout.close();
		fileName = new String(filenameWeb.getBytes("GBK"), "iso8859-1");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		wb.write(baos);
		istream = new ByteArrayInputStream(baos.toByteArray());
		baos.close();
	}

	public GameSpecialPriceService getGamePriceService() {
		return gamePriceService;
	}

	public void setGamePriceService(GameSpecialPriceService gamePriceService) {
		this.gamePriceService = gamePriceService;
	}

	public GameSpecialPriceQuery getGameSpecialPriceQuery() {
		return gameSpecialPriceQuery;
	}

	public void setGameSpecialPriceQuery(
			GameSpecialPriceQuery gameSpecialPriceQuery) {
		this.gameSpecialPriceQuery = gameSpecialPriceQuery;
	}

	public Pagination<?> getPage() {
		return page;
	}

	public void setPage(Pagination<?> page) {
		this.page = page;
	}

	public GameSpecialPrice getGameSpecialPrice() {
		return gameSpecialPrice;
	}

	public void setGameSpecialPrice(GameSpecialPrice gameSpecialPrice) {
		this.gameSpecialPrice = gameSpecialPrice;
	}

	public String getGoodsId() {
		return goodsId;
	}

	public void setGoodsId(String goodsId) {
		this.goodsId = goodsId;
	}

	@JSON(serialize = false)
	public String getTemplateCode() {
		return templateCode;
	}

	public void setTemplateCode(String templateCode) {
		this.templateCode = templateCode;
	}

	@JSON(serialize = true)
	public List<GoodsManageInfo> getGoodsIdList() {
		return goodsIdList;
	}

	public void setGoodsIdList(List<GoodsManageInfo> goodsIdList) {
		this.goodsIdList = goodsIdList;
	}

	public GamePriceTemplate getGameTemplate() {
		return gameTemplate;
	}

	public void setGameTemplate(GamePriceTemplate gameTemplate) {
		this.gameTemplate = gameTemplate;
	}

	public String getId() {
		return Id;
	}

	public void setId(String id) {
		Id = id;
	}

	public String getHighPrice() {
		return highPrice;
	}

	public void setHighPrice(String highPrice) {
		this.highPrice = highPrice;
	}

	public String getGoodsName() {
		return goodsName;
	}

	public void setGoodsName(String goodsName) {
		this.goodsName = goodsName;
	}

	public String getTempCode() {
		return tempCode;
	}

	public void setTempCode(String tempCode) {
		this.tempCode = tempCode;
	}

	public String getGoodId() {
		return goodId;
	}

	public void setGoodId(String goodId) {
		this.goodId = goodId;
	}

	public List<String> getGamePriceTemplate() {
		return gamePriceTemplate;
	}

	public void setGamePriceTemplate(List<String> gamePriceTemplate) {
		this.gamePriceTemplate = gamePriceTemplate;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getIstream() {
		return istream;
	}

	public void setIstream(InputStream istream) {
		this.istream = istream;
	}

	public String getTemplateName() {
		return templateName;
	}

	public void setTemplateName(String templateName) {
		this.templateName = templateName;
	}

	public List<String> getTemplateNameList() {
		return templateNameList;
	}

	public void setTemplateNameList(List<String> templateNameList) {
		this.templateNameList = templateNameList;
	}

	public String getBrandName() {
		return brandName;
	}

	public void setBrandName(String brandName) {
		this.brandName = brandName;
	}

	public List<GamePriceTemplate> getTemplateList() {
		return templateList;
	}

	public void setTemplateList(List<GamePriceTemplate> templateList) {
		this.templateList = templateList;
	}

	public List<GameSpecialPrice> getSpecialPriceList() {
		return specialPriceList;
	}

	public void setSpecialPriceList(List<GameSpecialPrice> specialPriceList) {
		this.specialPriceList = specialPriceList;
	}

}
